package com.ls.pattern.establish.prototype.deepclone;


import java.io.*;

public class DeepPrototype implements Serializable, Cloneable {
    private static final long serialVersionUID = -2802336008126905211L;

    public String name;
    public DeepCloneableTarget deepCloneableTarget;

    public DeepPrototype() {

    }

    //深拷贝 - 方式一 使用clone方法
    @Override
    protected DeepPrototype clone() throws CloneNotSupportedException {
        Object deep = null;
        //完成对基本数据类型属性的克隆
        deep = super.clone();

        //对引用类型属性进行处理
        DeepPrototype deepPrototype = (DeepPrototype) deep;

        deepPrototype.deepCloneableTarget = (DeepCloneableTarget) deepCloneableTarget.clone();

        return deepPrototype;
    }

    //深拷贝 - 方式二 通过对象的序列化(推荐)
    public DeepPrototype deepClone() {
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        DeepPrototype deep = null;
        try {
            //序列化
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);
            //反序列
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            deep = (DeepPrototype) ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                bos.close();
                oos.close();
                bis.close();
                ois.close();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }


        return deep;
    }


}
